#include "types.h"
#include "stdarg.h"
#include "console.h"
#include "number.h"
void print_int(int num);
void print_uint(unsigned int num, int base, int uppercase);
void print_pointer(uintptr_t ptr);

// 简单的格式化输出实现
int vprintf(const char *fmt, va_list ap) {
    int chars_printed = 0;
    
    for (int i = 0; fmt[i]; i++) {
        if (fmt[i] == '%') {
            i++;  // 跳过 '%'
            
            switch (fmt[i]) {
                case 'd':
                case 'i': {
                    int num = va_arg(ap, int);
                    print_int(num);
                    break;
                }
                
                case 'u': {
                    unsigned int num = va_arg(ap, unsigned int);
                    print_uint(num, 10, 1);
                    break;
                }
                
                case 'x': {
                    unsigned int num = va_arg(ap, unsigned int);
                    print_uint(num, 16, 0);
                    break;
                }
                
                case 'X': {
                    unsigned int num = va_arg(ap, unsigned int);
                    print_uint(num, 16, 1);
                    break;
                }
                
                case 'o': {
                    unsigned int num = va_arg(ap, unsigned int);
                    print_uint(num, 8, 1);
                    break;
                }
                
                case 'c': {
                    char c = (char)va_arg(ap, int);
                    console_putc(c);
                    chars_printed++;
                    break;
                }
                
                case 's': {
                    char *str = va_arg(ap, char*);
                    if (!str) str = "(null)";
                    console_puts(str);
                    break;
                }
                
                case 'p': {
                    void *ptr = va_arg(ap, void*);
                    print_pointer((uintptr_t)ptr);
                    break;
                }
                
                case '%': {
                    console_putc('%');
                    chars_printed++;
                    break;
                }
                
                default: {
                    // 未知格式，原样输出
                    console_putc('%');
                    console_putc(fmt[i]);
                    chars_printed += 2;
                    break;
                }
            }
        } else {
            console_putc(fmt[i]);
            chars_printed++;
        }
    }
    
    return chars_printed;
}

int printf(const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    int result = vprintf(fmt, ap);
    va_end(ap);
    return result;
}
